package client

import (
	"context"
	"fitness/rpc/proto/user"
	"google.golang.org/grpc"
)

type Handler func(ctx context.Context, in user.UserClient) (interface{}, error)

func UserClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8085", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := user.NewUserClient(dial)
	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	defer dial.Close()
	return res, nil
}

func UserLogin(ctx context.Context, i *user.UserLoginReq) (*user.UserLoginResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		login, err := in.UserLogin(ctx, i)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserLoginResp), nil
}

func FitnessList(ctx context.Context, i *user.FitnessListReq) (*user.FitnessListResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		list, err := in.FitnessList(ctx, i)
		if err != nil {
			return nil, err
		}
		return list, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.FitnessListResp), nil
}

func FitnessLike(ctx context.Context, i *user.FitnessLikeReq) (*user.FitnessListResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		like, err := in.FitnessLike(ctx, i)
		if err != nil {
			return nil, err
		}
		return like, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.FitnessListResp), nil
}
